const async = require("async");
module.exports = {
  handler(req,res,next){
    let userID = req.query.filter.userID;
    // let lastMessageCreateTime = req.query.sort.lastMessageCreateTime||1;
    // console.log("================"+lastMessageCreateTime)
    req.mongo.collection("user").find({"_id":userID}).next((e,r)=>{
      if(e) return res.err.mongoError(e);
      let conversationIDArray = r.conversationIDArray||[];
      async.auto([
          callback=>req.mongo.collection("conversation").aggregate([
            {$match:{"_id":{$in:conversationIDArray}}},
            {$unwind:"$talkerIDArray"},
            {$match:{"talkerIDArray":{$ne:userID}}},
            {$lookup:{
              from:"user",
              localField:"talkerIDArray",
              foreignField:"_id",
              as:"talkerIDArray"
            }},
            {$unwind:"$talkerIDArray"},
            // {$lookup:{
            //   from:"message",
            //   localField:"lastMessageID",
            //   foreignField:"_id",
            //   as:"lastMessage"
            // }},
            // {$unwind:"$lastMessage"},
            //
            // {$project:{
            //   "lastMessage.fromID":1,
            //   "lastMessage.readState":1,
            //   "lastMessage.content":1,
            //   "lastMessage.createTime":1,
            //   "talkerIDArray._id":1,
            //   "talkerIDArray.headPicPath":1,
            //   "talkerIDArray.nickname":1
            // }},
            {$sort:{"lastMessageDate":-1}}
          ]).toArray(callback)
      ],
          (e,result)=>{
            if(e) return res.err.mongoError(e);
            return res.reply({code:0,message:"查询成功",data:result[0]});
          }
      )
    })
  }
}